package com.retail.order.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class AliOSSUtils {
    @Autowired
    private AliOSSProperties aliOSSProperties;

    /**
     * 实现上传图片到oSS 普通上传
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public String upload(MultipartFile multipartFile) throws IOException {
        InputStream inputStream = multipartFile.getInputStream();
        String fileName = LocalDateTime.now().format(
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                + multipartFile
                .getOriginalFilename();
        // 上传文件到oss
        OSS ossClient = new OSSClientBuilder().build(aliOSSProperties.getEndPoint(),aliOSSProperties.getAccessKeyId(), aliOSSProperties.getAccessKeySecret());
        String url = "https://" + aliOSSProperties.getBucketName() + "." + aliOSSProperties.getEndPoint() + "/" +fileName;
        // 创建PutObjectRequest对象
        PutObjectRequest putObjectRequest = new PutObjectRequest(aliOSSProperties.getBucketName(), fileName, inputStream);
        // 创建PutObject请求
        PutObjectResult result = ossClient.putObject(putObjectRequest);
        return url;
    }

}
